package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.model.User;
import com.example.demo.model.UserBook;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserBookMapper extends BaseMapper<UserBook> {
    @Insert("INSERT INTO reader_book (user_id, book_id) VALUES (#{userId}, #{bookId})")
    void insertBorrowRecord(Long userId, Long bookId);

    @Delete("DELETE FROM reader_book WHERE user_id = #{userId} AND book_id = #{bookId}")
    void deleteBorrowRecord(Long userId, Long bookId);

    @Select("SELECT EXISTS(SELECT 1 FROM reader_book WHERE user_id = #{userId} AND book_id = #{bookId})")
    boolean existsBorrowRecord(Long userId, Long bookId);
    @Select("SELECT * FROM reader_book")
    List<UserBook> selectAllRecords();


    @Select("SELECT ub.*, u.name AS username, b.title AS title " +
            "FROM reader_book ub " +
            "LEFT JOIN user u ON ub.user_id = u.id " +
            "LEFT JOIN book b ON ub.book_id = b.id " +
            "WHERE ub.id = #{recordId} " +
            "AND (b.title LIKE CONCAT('%', #{title}, '%') OR #{title} IS NULL) " +
            "AND (u.name LIKE CONCAT('%', #{borrowerUsername}, '%') OR #{borrowerUsername} IS NULL)")
    Page<UserBook> selectUserBookByIdWithPaging(@Param("recordId") Long recordId,
                                                @Param("title") String title,
                                                @Param("borrowerUsername") String borrowerUsername,
                                                Page<UserBook> page);


    User findByUsername(String username);
}
